package com.itheima.reggie.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登陆方法
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据页面提交的用户名username查询数据库中员工数据信息
       // String username = employee.getUsername();
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);
//        如果没有查询到, 则返回登录失败结果
        if (null == emp) {
            return R.error("登陆失败");
        }
        //密码比对，如果不一致, 则返回登录失败结果
        if (!password.equals(emp.getPassword())) {
            return R.error("登陆失败");
        }
//        查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        Integer status = emp.getStatus();
        if (0 == status) {
            return R.error("账号已禁用");
        }
//        登录成功，将员工id存入Session, 并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    // 接收页面发送的POST请求 /employee/logout,退出清除id
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    //新增员工
    @PostMapping
    @CacheEvict(value = "employeeCach",allEntries = true)
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //获取登录信息中的id
        Long id = (Long) request.getSession().getAttribute("employee");
        // 设置操作人id和时间,以及初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        employee.setCreateUser(id);
//        employee.setUpdateUser(id);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        try {
            boolean flag = employeeService.save(employee);
        } catch (Exception ex) {
            return R.success("新增员工失败");
        }
        //boolean flag = employeeService.save(employee);
        return R.success("新增员工成功");
    }

//分页查询
    @Cacheable(value = "employeeCach",key ="#page+'and'+#pageSize" )
    @GetMapping("/page")
    public R<Page> selecedPage(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);
//        String key = page + "and" + pageSize;
//        String vulue = (String) redisTemplate.opsForValue().get(key);
//        if (vulue == null) {
            //  设置分页构造器
            Page pageInfo = new Page(page, pageSize);
    //        获取查询表达式
            LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
            //输入查询条件，并且要输入与否都可以
            lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
            //设置查询条件，按照创建时间倒叙
            lqw.orderByDesc(Employee::getUpdateTime);
            //执行分页查询
            Page page1 = employeeService.page(pageInfo, lqw);
            //把分页对象转化为JSON存到redis
        //    String toJSONString = JSON.toJSONString(page1);
        //    redisTemplate.opsForValue().set(key, toJSONString);
            return R.success(page1);
//        } else {
//            Page page1 = JSON.parseObject(vulue, Page.class);
//            return R.success(page1);
//        }
    }


    @PutMapping
    @CacheEvict(value = "employeeCach",allEntries = true)
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
        //获取存在session域中的Id
       // Long empId = (Long) request.getSession().getAttribute("employee");
        //更新修改时间
      //  employee.setUpdateTime(LocalDateTime.now());
        //更新修改人Id
      //  employee.setUpdateUser(empId);
        //修改该条数据
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employeeById = employeeService.getById(id);
        if (null!= employeeById){
            return R.success(employeeById);
        }
        return R.error("查询没有此员工");
    }
}
